import util from '@/libs/util';
import books from '../book/bookList.vue';
import studentList from '../studentsignup/studentList.vue';
import regs from  '../../util/formReg';

export default {
    components: {books, studentList},
    data () {
        return {
            columns: [{
                title: '序号',
                key: 'rownum',
                align: 'center',
                width: 60,
                render: (h, params) => {
                    return h('div', {}, ((this.pageIndex - 1) * this.pageSize + params.index + 1));
                }
            },  {
                title: '订单号',
                key: 'code'
            },{
                title: '学生姓名',
                key: 'studentName'
            }, {
                title: '教材名称',
                key: 'bookName'
            }, {
                title: '创建时间',
                key: 'createTime',
                render: (h, params) => {
                    return h('span', {}, util.getDate(params.row.createTime, 'time'));
                }
            }, {
                title: '支付时间',
                key: 'payTime',
                render: (h, params) => {
                    return h('span', {}, util.getDate(params.row.payTime, 'time'));
                }
            }, {
                title: '订单支付金额',
                key: 'realAmt'
            }, {
                title: '状态',
                key: 'status',
                render: function (h, params) {
                    let text = '';
                    let status = params.row.status;
                    if (status == 1) {
                        text = '待缴费';
                    } else if (status == 2) {
                        text = '已缴费';
                    } else if (status == 3) {
                        text = '申请退款';
                    } else if (status == 4) {
                        text = '已退款';
                    } else if (status == 5) {
                        text = '已失效';
                    }
                    return h('div', {}, text);
                }
            }, {
                title: '操作',
                key: 'action',
                width: 200,
                align: 'center',
                render: (h, params) => {
                    if (params.row.status == 1) {
                        return h('div', [
                            h('Button', {
                                props: {
                                    type: 'primary',
                                    size: 'small'
                                },
                                style: {
                                    marginRight: '5px'
                                },
                                on: {
                                    click: () => {
                                        this.approve(params.row);
                                    }
                                }
                            }, '现金缴费'),
                            h('Button', {
                                props: {
                                    type: 'success',
                                    size: 'small'
                                },
                                style: {
                                    marginRight: '5px'
                                },
                                on: {
                                    click: () => {
                                        this.weChatPayModal=true;
                                        this.orderDetails={};
                                        this.payNum='';
                                      this.settleWechatPay(params.row);
                                    }
                                }
                            }, '微信缴费'),
                            h('Button', {
                                props: {
                                    type: 'error',
                                    size: 'small'
                                },
                                style: {
                                    marginRight: '5px'
                                },
                                on: {
                                    click: () => {
                                        this.delete(params.row.id);
                                    }
                                }
                            }, '删除')
                        ]);
                    }else if(params.row.status==2){
                       return h('Button', {
                            props: {
                                type: 'success',
                                size: 'small'
                            },
                            style: {
                                marginRight: '5px'
                            },
                            on: {
                                click: () => {
                                    util.ajax.post('/busine/bill/article/getPayShit', util.toFormData({// 查询打印数据
                                        id: params.row.id
                                    })).then(res => {
                                        this.$router.push({
                                            path: 'test',
                                            name: 'test',
                                            params: {
                                                data: res.data.data,
                                                entry: 1// 入口
                                            }
                                        });
                                    });
                                }
                            }
                        }, '打印票据')
                    }
                }
            }],

            studentModal: false,
            dataList: [],
            form: {
                name: '',
                parentphone: ''
            },
            forms: {
                name: ''
            },
            formDataRules: {// 添加班级表单验证规则
                otherCost: [
                    { required: true, message: '请选择教材', trigger: 'blur'}
                ]
            },
            booksVisible: false,
            addVisible: false, // 新增弹窗的显示和隐藏
            formData: {
                otherCost: 0
            }, // 新增/编辑表单数据
            queryData: {
                StudentName: '',
                bookName: ''
            }, // 查询表单数据
            pageSize: 10, // 分页数据
            pageIndex: 1, // 分页数据
            total: 0,
            bookList: [],
            ids: [],
            weChatPayModal:false,
            payNum:'',
            orderDetails:{},
            payLoading:false,
        };
    },
    mounted () {
        this.doQuery();
    },
    methods: {
        doQuery () {
            util.ajax.post('/busine/bill/article/list', util.toFormData({
                page: this.pageIndex,
                size: this.pageSize,
                bookName: this.queryData.bookName,
                StudentName: this.forms.name
            })).then(res => {
                if (res.data.data) {
                    this.dataList = res.data.data.list;
                    this.total = res.data.data.total;
                }
            });
        },
        refresh () {
            this.forms = {
                name: ''
            };
            this.form = {
                name: '',
                parentphone: ''
            };
            this.queryData = {
                StudentName: '',
                bookName: ''
            };
            this.doQuery();
        },
        showAdd: function (obj) {
            // this.forms = {};
            // this.form = {};
            // this.formData = {};
            this.bookList = [];
            this.addVisible = true;
            // this.$refs.books.ids = '';
            // this.$refs.books.books = [];
        },
        delete (id) {
            this.$Modal.confirm({
                title: '提示',
                content: '<p>确定删除？</p>',
                onOk: () => {
                    util.ajax.post('/busine/bill/article/delete', util.toFormData({id: id})).then(res => {
                        if (res.data.code == 200 && res.data.message == 'SUCCESS') {
                            this.$Message.success('操作成功！');
                            this.doQuery();
                        } else {
                            this.$Message.success('操作失败！');
                        }
                    });
                },
                onCancel: () => {
                }
            });
        },
        doSave: function () {
            // this.formData = {
            //     otherCost: 0
            // };
            let formData = this.formData;
            this.formData.bookList = this.$refs.books.books;
            let bookList = this.formData.bookList;
            let ids = '';
            for (let i in bookList) {
                ids += bookList[i].id + ',';
            }
            if (ids.length > 0) {
                ids = ids.substr(0, ids.length - 1);
            }
            this.formData.bookId = ids;
            formData.bookId = this.formData.bookId;
            formData.otherCost = formData.bookList.length <= 0 ? '' : JSON.stringify(formData.bookList);
            let studentId = this.form.id;
            formData.studentId = studentId;
            this.$refs['formData'].validate((valid) => { // 表单验证
                if (valid) {
                    if (studentId != null && studentId != '' && studentId != undefined) {
                        util.ajax.post('/busine/bill/article/save', util.toFormData(formData)).then(res => {
                            if (res.data.code == 200) {
                                if (res.data.message == 'SUCCESS') {
                                    this.$Message.success('保存成功！');
                                    this.pageIndex = 1;
                                } else {
                                    this.$Message.warning(res.data.message || '未知错误！');
                                }
                                this.addVisible = false;
                                this.refresh();
                                this.form = {};
                                this.forms = {};
                                this.formData = {};
                                this.bookList = [];
                            }
                        });
                    } else { // 保存学生再进行购买教材的操作
                        util.ajax.post('/busine/student/save', util.toFormData(this.form)).then(res => {
                            if (res.data.code == 200) {
                                formData.studentId = res.data.data.id;
                                util.ajax.post('/busine/bill/article/save', util.toFormData(formData)).then(res => {
                                    if (res.data.code == 200) {
                                        this.initBooksInfo();
                                        if (res.data.message == 'SUCCESS') {
                                            this.$Message.success('保存成功！');
                                            this.pageIndex = 1;
                                        } else {
                                            this.$Message.warning(res.data.message || '未知错误！');
                                        }
                                        this.addVisible = false;
                                    }
                                });
                            } else {
                                this.$Message.error(res.data.message);
                            }
                        });
                    }
                } else {
                    this.$Message.warning('请检查输入项！');
                }
            });
        },
        setStudent () {
            this.form = {};
            this.isRead = true;
            this.form = this.$refs.student.student;
            this.form.isEat = 'YES';
            this.form.chargeValidity = new Date(((new Date()).getTime() + (24 * 60 * 60 * 1000)));
        },
        whenSelectBook: function () {
            this.bookList = this.$refs.books.books;
            // 计算教材费
            let bookList = this.bookList;
            let total = 0;
            for (let i in bookList) {
                let price = bookList[i].price;
                total += price;
                this.ids.push(bookList[i].id);
            }
            this.formData.realAmt = total;
        },
        approve: function (obj) {
            if (obj.status == 2) {
                this.$Message.error('已缴费，不可再缴费!');
            } else {
                util.ajax.post('/busine/bill/article/updateStatus', util.toFormData({
                    id: obj.id
                })).then(res => {
                    if (res.data.message) {
                        this.$Message.success('操作成功!');
                    } else {
                        this.$Message.error('操作失败!');
                    }
                    this.refresh();
                });
            }
        },
        whenDelBooks: function (event, name) {
            var id = name.id;
            var delIndex = '';
            var list = this.bookList;
            for (let i in list) {
                if (list[i].id != null && list[i].id != '' && list[i].id != undefined) {
                    if (id == list[i].id) {
                        delIndex = i;
                        break;
                    }
                }
            }
            this.ids.splice(delIndex, 1);
            this.bookList.splice(delIndex, 1);
        },
        queryByName: function () {
            let name = this.form.name;
            util.ajax.post('/busine/student/queryByName', util.toFormData({
                name: name
            })).then(res => {
                if (res.data.code == 200) {
                    // noinspection JSAnnotator
                    if (res.data.data == '' || res.data.data == '' || res.data.data == undefined) {
                        // donothing
                    } else {
                        this.form = res.data.data;
                    }
                } else {
                    this.$Message.error(res.data.message);
                }
            });
        },
        addBooks: function () {
            this.booksVisible = true;
        },
        initBooksInfo: function () {
            this.bookList = [];
            this.ids = [];
        },
        payByWechat: function () {
            this.$Modal.confirm({
                title: '提示',
                content: '确认应收金额:' + this.orderDetails.real_amt + '(元)?',
                onOk: () => {
                    this.payLoading=true;
                    this.payNumVisible = true;
                    let payNum = this.payNum;
                    if (regs.isNotEmpty(payNum)) {
                        this.$Message.loading({
                            content: '支付中请稍后...',
                            duration: 0,
                            closable: true
                        });
                        util.ajax.post('/busine/bill/article/wechatPay', util.toFormData({
                            id: this.orderDetails.id,
                            payNum: payNum
                        })).then(res => {
                            this.payLoading=false;
                            if (res.data.code == 1000) { // 免密支付成功
                                this.$Message.destroy();
                                this.$Notice.open({
                                    title: '支付消息',
                                    desc: '支付成功！',
                                    duration: 0
                                });
                                this.doQuery();
                                this.weChatPayModal=false;
                                // this.orderDetails.id = res.data.data.id;
                                // this.cleanPayShit();
                                //
                                // let data = res.data.data;
                                // data.student_name = this.orderDetails.name;
                                // data.real_amt = this.orderDetails.real_amt;
                                // let params = {
                                //     data: data,
                                //     entry: 2// 入口
                                // };
                                // this.goInvoicePage(params);
                                // this.queryWechatResult();
                            } else if (res.data.code == 1001 || res.data.code == 100) {
                                this.$Message.destroy();
                                this.$Notice.open({
                                    title: '支付消息',
                                    desc: res.data.message,
                                    duration: 0
                                });
                                // this.cleanPayShit();
                            } else if (res.data.code == 1002) {
                                this.queryWechatResult();
                            }
                        });
                    }else{
                        this.$Message.warning('支付条码为空');
                        this.payLoading=false;
                    }
                },
                onCancel: () => {

                }
            });
        },
        queryWechatResult: function () {
            util.ajax.post('/busine/bill/article/wechatQuery', util.toFormData({
                id: this.orderDetails.id
            })).then(res => {
                this.payLoading=false;
                if (res.data.code == 1000) {
                    this.$Message.destroy();
                    this.$Notice.open({
                        title: '支付消息',
                        desc: '支付成功!',
                        duration: 0
                    });
                    this.doQuery();
                    this.weChatPayModal=false;
                    // let data = res.data.data;
                    // data.student_name = this.orderDetails.name;
                    // data.real_amt = this.orderDetails.real_amt;
                    // let params = {
                    //     data: data,
                    //     entry: 2// 入口
                    // };
                    // this.goInvoicePage(params);
                } else if (res.data.code == 500 || res.data.code == 100) { // 业务逻辑错误
                    this.$Notice.open({
                        title: '支付消息',
                        desc: res.data.message,
                        duration: 0
                    });
                    // this.cleanPayShit();
                } else {
                    this.queryWechatResult();
                }
            });
        },
        settleWechatPay:function (data) {
            this.orderDetails.id=data.id;
            this.orderDetails.real_amt=data.realAmt;
        }
    }
};
